# -*- coding:utf8 -*-
from __future__ import print_function, unicode_literals
import os

server_map = {
    "company": {
        "NewCommonUtility": "/media/spiriy/OS/D/NewCommonUtility",
        "ProjectsDir": [
            "/media/spiriy/OS/D"
        ]
    },
    'da02': {
        "NewCommonUtility": "/data/projects/NewCommonUtility",
        "ProjectsDir": [
            "/data/projects",
        ]
    },
    'search': {
        "NewCommonUtility": '/data/projects/NewCommonUtility',
        "ProjectsDir": [
            "/data/projects",
        ]
    },
    'home': {
        "NewCommonUtility": '/home/spirit/projects/NewCommonUtility',
        "ProjectsDir": [
            "/home/spirit/projects",
            "/home/spirit/javaprojects",
            "/home/spirit/djangoprojects",
        ]
    }
}


def create_cmd(file, port=None, server='company', type_='flask', project_local=None, project_target=None):
    """
    创建执行命令，有多种方式
    :return:
    """
    if not file.startswith('/') and ':' not in file:
        raise Exception("File Must Be Absoulute! You Can Use __file__ Instead!")

    # 本地
    dir_local = os.path.dirname(file)
    file_full = os.path.basename(file)
    file_base = file.replace('.py', '')
    if project_local is None:
        project_local = server_map.get('company').get("ProjectsDir")
    else:
        project_local = [project_local]

    dict_target = server_map.get(server)
    common_target = dict_target['NewCommonUtility']
    if project_target is None:
        project_target = dict_target.get('ProjectsDir')
    else:
        project_target = [project_target]

    project_all = project_local + project_target
    curr_dir = dir_local
    while os.path.dirname(curr_dir) not in project_all:
        curr_dir = os.path.dirname(curr_dir)
        if not curr_dir:
            break

    project_name = os.path.basename(curr_dir)
    project_local_ = os.path.dirname(curr_dir)
    project_target_ = curr_dir.replace(project_local_, project_target[0])
    dir_target = dir_local.replace(project_local_, project_target_)

    if type_.startswith('fla'):
        print("cd {}".format(dir_target))
        print("PYTHONPATH='{}:{}' LogTerm=1 python {} -p {}".format(project_target_, common_target, file, port))
        supvisor_template = """
# 采用supervisord方式进行控制
[program:{project_name}_{port}]
user=spirit
command=python {file} -p {port}
directory={dir_}
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile={project_dir}/logs/Supervisor.{project_name}.Server.Flask.Runtime.{port}.log
environment=PYTHONPATH="{project_dir}:{common_dir}",LogTerm=1
""".format(
            file=file_full,
            port=port,
            project_name=project_name,
            project_dir=project_target_,
            dir_=dir_target,
            common_dir=common_target
    )
        print(supvisor_template)

    elif type_.startswith('gun'):
        print("cd {}".format(dir_target))
        print("PYTHONPATH='{}:{}' gunicorn -b 0.0.0.0:{} -w 1 -k gevent {}:app".format(
            project_target_,
            common_target,
            port,
            file_base))
        supvisor_template = """
# 采用supervisord方式进行控制
[program:{project_name}_{port}]
user=spirit
command=gunicorn -b 0.0.0.0:{port} -w 1 -k gevent {file}:app
directory={dir_}
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile={project_dir}/logs/Supervisor.{project_name}.Server.Gunicorn.Runtime.{port}.log
environment=PYTHONPATH="{project_dir}:{common_dir}",LogTerm=1
""".format(
            file=file_base,
            port=port,
            project_name=project_name,
            project_dir=project_target_,
            dir_=dir_target,
            common_dir=common_target
        )
        print(supvisor_template)


# 使用方法
'''
from code_template.gunicorn_flask import create_cmd
create_cmd(__file__, port=10066, server='local')
'''
